import React, { useState, useEffect, memo, useMemo } from 'react';
import PropTypes from 'prop-types';
import { debounce } from 'lodash';
import { InputNumber, Button, Select, Tooltip, ColorPicker, Slider } from 'antd';
import {
    BoldOutlined,
    ItalicOutlined,
    UnderlineOutlined,
    StrikethroughOutlined
} from '@ant-design/icons';

import { ColorUtils } from '../../utils/utils';
import './toolBar.css';

const { Option } = Select;

const Toolbar = ({
    onChangeBackgroundColor = () => {},
    onChangeBorderWidth = () => {},
    onChangeBorderColor = () => {},
    onBringToFront = () => {},
    onSendToBack = () => {},
    onTextAttributeChange = () => {},
    onDeleteObject = () => {},
    onResetZoom = () => {},
    selectedObjects = [],
    zoom = 1,
    onZoomChange = () => {},
    onSaveCanvas = () => {} // 明确添加默认处理
}) => {
    // 预定义的颜色选择
    const colors = [
        '#f44336',
        '#e91e63',
        '#9c27b0',
        '#673ab7',
        '#3f51b5',
        '#2196f3',
        '#03a9f4',
        '#00bcd4',
        '#009688',
        '#4caf50',
        '#8bc34a',
        '#cddc39',
        '#ffeb3b',
        '#ffc107',
        '#ff9800',
        '#ff5722',
        '#795548',
        '#9e9e9e',
        '#607d8b',
        '#000000',
        '#ffffff'
    ];

    // 添加状态跟踪自定义颜色输入
    const [customBgColor, setCustomBgColor] = useState('#ffffff');
    const [customBorderColor, setCustomBorderColor] = useState('#000000');

    // 文本样式状态
    const [fontFamily, setFontFamily] = useState('Arial');
    const [fontSize, setFontSize] = useState(20);
    const [isBold, setIsBold] = useState(false);
    const [isItalic, setIsItalic] = useState(false);
    const [isUnderline, setIsUnderline] = useState(false);
    const [isLinethrough, setIsLinethrough] = useState(false);

    // 字体列表
    const fonts = [
        'Arial',
        'SimSun', // 宋体
        'KaiTi', // 楷体
        'SimHei', // 黑体
        'Microsoft YaHei', // 微软雅黑
        'NSimSun', // 新宋体
        'FangSong' // 仿宋
    ];

    // 当selectedObjects改变时更新状态
    useEffect(() => {
        if (selectedObjects.length === 1) {
            const obj = selectedObjects[0];
            setCustomBgColor(obj.fill || '#ffffff');
            setCustomBorderColor(obj.stroke || '#000000');

            // 如果是文本对象，更新文本相关状态
            if (obj.type === 'textbox' || obj.type === 'i-text' || obj.type === 'text') {
                // 检查是否有选中的文本
                const selectionStyles = obj.getSelectedTextStyles?.();
                if (selectionStyles) {
                    // 如果有选中的文本，使用选中文本的样式
                    setFontFamily(selectionStyles.fontFamily || 'Arial');
                    setFontSize(selectionStyles.fontSize || 20);
                    setIsBold(selectionStyles.fontWeight === 'bold');
                    setIsItalic(selectionStyles.fontStyle === 'italic');
                    setIsUnderline(selectionStyles.underline || false);
                    setIsLinethrough(selectionStyles.linethrough || false);
                } else {
                    // 否则使用整个文本对象的样式
                    setFontFamily(obj.fontFamily || 'Arial');
                    setFontSize(obj.fontSize || 20);
                    setIsBold(obj.fontWeight === 'bold');
                    setIsItalic(obj.fontStyle === 'italic');
                    setIsUnderline(obj.underline || false);
                    setIsLinethrough(obj.linethrough || false);
                }
            }
        } else if (selectedObjects.length > 1) {
            // 多选时重置为默认值
            setCustomBgColor('#ffffff');
            setCustomBorderColor('#000000');
            setFontFamily('Arial');
            setFontSize(20);
            setIsBold(false);
            setIsItalic(false);
            setIsUnderline(false);
            setIsLinethrough(false);
        } else {
            // 没有选中对象时重置为默认值
            setCustomBgColor('#ffffff');
            setCustomBorderColor('#000000');
            setFontFamily('Arial');
            setFontSize(20);
            setIsBold(false);
            setIsItalic(false);
            setIsUnderline(false);
            setIsLinethrough(false);
        }
    }, [selectedObjects]);

    // 文本属性改变处理函数
    const handleFontFamilyChange = (value) => {
        setFontFamily(value);
        onTextAttributeChange?.('fontFamily', value);
    };

    const handleFontSizeChange = (value) => {
        setFontSize(value);
        onTextAttributeChange?.('fontSize', value);
    };

    const handleTextColorChange = (color) => {
        console.log('Text color changed to:', color);
        onTextAttributeChange?.('fill', color);
    };

    const handleBoldToggle = () => {
        const newValue = !isBold;
        setIsBold(newValue);
        onTextAttributeChange?.('fontWeight', newValue ? 'bold' : 'normal');
    };

    const handleItalicToggle = () => {
        const newValue = !isItalic;
        setIsItalic(newValue);
        onTextAttributeChange?.('fontStyle', newValue ? 'italic' : 'normal');
    };

    const handleUnderlineToggle = () => {
        const newValue = !isUnderline;
        setIsUnderline(newValue);
        onTextAttributeChange?.('underline', newValue);
    };

    const handleLinethroughToggle = () => {
        const newValue = !isLinethrough;
        setIsLinethrough(newValue);
        onTextAttributeChange?.('linethrough', newValue);
    };

    // 防抖函数
    const debouncedBgColorChange = useMemo(
        () =>
            debounce((color) => {
                const hexColor = color.toHexString();
                setCustomBgColor(hexColor);
                onChangeBackgroundColor(hexColor);
            }, 100),
        [onChangeBackgroundColor]
    );

    const debouncedBorderColorChange = useMemo(
        () =>
            debounce((color) => {
                const hexColor = color.toHexString();
                setCustomBorderColor(hexColor);
                onChangeBorderColor(hexColor);
            }, 100),
        [onChangeBorderColor]
    );

    const debouncedTextColorChange = useMemo(
        () =>
            debounce((color) => {
                handleTextColorChange(color.toHexString());
            }, 100),
        [handleTextColorChange]
    );

    // 检查是否为文本对象
    const isTextObject =
        selectedObjects.length === 1 &&
        (selectedObjects[0].type === 'textbox' ||
            selectedObjects[0].type === 'i-text' ||
            selectedObjects[0].type === 'text');

    // 清理防抖函数
    useEffect(() => {
        return () => {
            debouncedBgColorChange.cancel();
            debouncedBorderColorChange.cancel();
            debouncedTextColorChange.cancel();
        };
    }, [debouncedBgColorChange, debouncedBorderColorChange, debouncedTextColorChange]);

    return (
        <div className="toolbar-component">
            {selectedObjects.length > 0 ? (
                <>
                    {/* 普通对象样式控制 */}
                    {!isTextObject && (
                        <>
                            <div className="toolbar-group">
                                <label>背景色：</label>
                                <ColorPicker
                                    value={customBgColor}
                                    onChange={debouncedBgColorChange}
                                    presets={[
                                        {
                                            label: '预设颜色',
                                            colors: colors
                                        }
                                    ]}
                                    size="small"
                                    trigger="click"
                                    showText
                                />
                            </div>

                            <div className="toolbar-group">
                                <label>边框宽度：</label>
                                <InputNumber
                                    min={0}
                                    max={50}
                                    defaultValue={
                                        selectedObjects.length === 1
                                            ? selectedObjects[0].strokeWidth || 0
                                            : 0
                                    }
                                    onChange={(value) => onChangeBorderWidth(value)}
                                    size="small"
                                    controls={true}
                                    className="width-input"
                                    style={{ fontSize: '11px', height: '22px' }}
                                />
                            </div>

                            <div className="toolbar-group">
                                <label>边框颜色：</label>
                                <ColorPicker
                                    value={customBorderColor}
                                    onChange={debouncedBorderColorChange}
                                    presets={[
                                        {
                                            label: '预设颜色',
                                            colors: colors
                                        }
                                    ]}
                                    size="small"
                                    trigger="click"
                                    showText
                                />
                            </div>
                        </>
                    )}

                    {/* 文本对象专用控制 */}
                    {isTextObject && (
                        <>
                            <div className="toolbar-group">
                                <label>字体：</label>
                                <Select
                                    value={fontFamily}
                                    onChange={handleFontFamilyChange}
                                    style={{ width: 150 }}
                                    size="small"
                                >
                                    {fonts.map((font) => (
                                        <Option
                                            key={font}
                                            value={font}
                                            style={{ fontFamily: font }}
                                        >
                                            {font}
                                        </Option>
                                    ))}
                                </Select>
                            </div>

                            <div className="toolbar-group">
                                <label>字号：</label>
                                <InputNumber
                                    min={8}
                                    max={100}
                                    value={fontSize}
                                    onChange={handleFontSizeChange}
                                    size="small"
                                    controls={true}
                                    className="width-input"
                                    style={{ fontSize: '11px', height: '22px' }}
                                />
                            </div>

                            <div className="toolbar-group">
                                <label>文字颜色：</label>
                                <ColorPicker
                                    value={
                                        selectedObjects.length === 1
                                            ? selectedObjects[0]?.fill || '#000000'
                                            : '#000000'
                                    }
                                    onChange={debouncedTextColorChange}
                                    presets={[
                                        {
                                            label: '预设颜色',
                                            colors: colors
                                        }
                                    ]}
                                    size="small"
                                    trigger="click"
                                    showText
                                />
                            </div>

                            <div className="toolbar-group">
                                <label>背景色：</label>
                                <div className="color-picker">
                                    {colors.map((color, index) => (
                                        <div
                                            key={index}
                                            className="color-option"
                                            style={{ backgroundColor: color }}
                                            onClick={() =>
                                                onTextAttributeChange?.('backgroundColor', color)
                                            }
                                            title={color}
                                        />
                                    ))}
                                </div>
                            </div>

                            <div className="toolbar-group">
                                <label>样式：</label>
                                <div className="text-format-buttons">
                                    <Tooltip title="粗体">
                                        <Button
                                            size="small"
                                            type={isBold ? 'primary' : 'default'}
                                            icon={<BoldOutlined />}
                                            onClick={handleBoldToggle}
                                        />
                                    </Tooltip>
                                    <Tooltip title="斜体">
                                        <Button
                                            size="small"
                                            type={isItalic ? 'primary' : 'default'}
                                            icon={<ItalicOutlined />}
                                            onClick={handleItalicToggle}
                                        />
                                    </Tooltip>
                                    <Tooltip title="下划线">
                                        <Button
                                            size="small"
                                            type={isUnderline ? 'primary' : 'default'}
                                            icon={<UnderlineOutlined />}
                                            onClick={handleUnderlineToggle}
                                        />
                                    </Tooltip>
                                    <Tooltip title="删除线">
                                        <Button
                                            size="small"
                                            type={isLinethrough ? 'primary' : 'default'}
                                            icon={<StrikethroughOutlined />}
                                            onClick={handleLinethroughToggle}
                                        />
                                    </Tooltip>
                                </div>
                            </div>
                        </>
                    )}

                    {/* 所有对象都可以使用图层控制 */}
                    <div className="toolbar-group">
                        <label>图层顺序：</label>
                        <div className="layer-buttons ">
                            <Button
                                size="small"
                                onClick={onBringToFront}
                                title="置于顶层"
                                className="layer-button animate__animated animate__rubberBand"
                                type="primary"
                            >
                                置顶
                            </Button>
                            <Button
                                size="small"
                                onClick={onSendToBack}
                                title="置于底层"
                                className="layer-button animate__animated animate__rubberBand"
                                type="primary"
                            >
                                置底
                            </Button>
                            <Button
                                size="small"
                                type="danger"
                                onClick={onDeleteObject}
                                title="删除选中对象"
                                className="layer-button animate__animated animate__rubberBand"
                                disabled={selectedObjects.length === 0}
                            >
                                删除
                            </Button>
                        </div>
                    </div>
                </>
            ) : (
                <>
                    <div className="toolbar-group">
                        <label>画布缩放：</label>
                        <Tooltip title="调整画布缩放比例" placement="bottom">
                            <Slider
                                min={0.1}
                                max={3.0}
                                step={0.1}
                                value={zoom}
                                onChange={(value) => {
                                    console.log('Slider value changed:', value);
                                    onZoomChange(value);
                                }}
                                style={{ width: 150 }}
                                tooltip={{ formatter: (value) => `${(value * 100).toFixed(0)}%` }}
                                disabled={false}
                            />
                        </Tooltip>
                    </div>
                    <div className="no-selection-message">请选择图形或文本</div>
                </>
            )}
        </div>
    );
};

export default memo(Toolbar, (prevProps, nextProps) => {
    // 比较selectedObjects数组是否相同
    const isSelectedObjectsSame =
        prevProps.selectedObjects.length === nextProps.selectedObjects.length &&
        prevProps.selectedObjects.every((obj, i) => obj === nextProps.selectedObjects[i]);

    return (
        isSelectedObjectsSame &&
        prevProps.zoom === nextProps.zoom &&
        prevProps.onZoomChange === nextProps.onZoomChange &&
        prevProps.onBrushModeChange === nextProps.onBrushModeChange &&
        prevProps.onBrushDottedChange === nextProps.onBrushDottedChange &&
        prevProps.onDotDensityChange === nextProps.onDotDensityChange &&
        prevProps.isBrushActive === nextProps.isBrushActive
    );
});
